package com.myworkbench.workbench.domain.entity.user;

import com.myworkbench.workbench.domain.Identity;
import com.myworkbench.workbench.domain.common.IsDelete;
import com.myworkbench.workbench.domain.entity.resource.Resource;
import com.myworkbench.workbench.domain.entity.resource.ResourceId;
import com.myworkbench.workbench.domain.entity.role.Role;
import com.myworkbench.workbench.domain.entity.role.RoleId;
import com.myworkbench.workbench.domain.valueobject.Creator;
import com.myworkbench.workbench.domain.valueobject.Updator;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.util.Assert;

import javax.persistence.*;
import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Data
@Table
@Entity
@AllArgsConstructor
@NoArgsConstructor
public class User  extends Identity<User>  implements Serializable {

    @Transient
    private UserId userId;
    @Column(length = 50,nullable = false)
    private String realName;
    @Column(length = 50,nullable = false)
    private String loginName;
    @Column(length = 32,nullable = false)
    private String password;
    @Column(length = 32)
    private String email;
    @Column(length = 32)
    private String qq;

    private LocalDateTime lastLoginTime;

    @Column(length = 4)
    private  Integer loginCount;

    private Short isDelete;
    //    用户关联角色

    public UserId getUserId() {
        return new UserId(this.getId());
    }

    @Embedded
    @ElementCollection(fetch = FetchType.LAZY)
    @CollectionTable(name="rel_user_role",
            joinColumns ={@JoinColumn(name = "user_id")})
    @AttributeOverrides({ @AttributeOverride(name="id",column = @Column(name="role_id"))})
    private Set<RoleId>  roleIds;

    /**
     * 用户授权
     * @param roleIds
     */
    public  void grantRole(Set<RoleId> roleIds){
        Assert.notEmpty(roleIds,"roleIds is null");
        User user = get();
        Assert.notNull(user,"user is null ");
        user.setRoleIds(roleIds);
        user.update();
    }

    /**
     *  值对象
     */
    private Creator creator;
    private Updator updator;
}
